#!/usr/bin/python
# -*- coding: utf-8 -*-
# $Revision$
# $Date$$


from __init__ import _
from enigma import *
from Screens.Screen import Screen
from Screens.Console import Console
from Components.ActionMap import ActionMap, NumberActionMap
from Components.ScrollLabel import ScrollLabel
from Components.MenuList import MenuList
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from Components.Sources.StaticText import StaticText
from Components.Label import Label
from Tools.Directories import fileExists
from Plugins.Plugin import PluginDescriptor


import os
import re
import subprocess


#Variablen
version = "0.1"
path =  '/usr/lib/enigma2/python/Plugins/Extensions/DreamDropbox'

#Skinaufloesung Herausfinden
offset = 20
font_size = 20
if int(getDesktop(0).size().width()) > 720:
    used_skin = "hd"
    scale_x = 1.8
    scale_y = 1.25
else:
    used_skin = "sd"
    scale_x = 1
    scale_y = 1
    
def autostart(reason, **kwargs):
    if reason == 0:
        print "[DREAMDROPBOX] no autostart"
        
def Plugins(**kwargs):
    if os.path.exists("/usr/lib/enigma2/python/Plugins/Bp/geminimain"):
        return [PluginDescriptor(name = "DreamDropbox Ver. %s" % (version), description = _("Dropbox client for Enigma2"), where = PluginDescriptor.WHERE_PLUGINMENU, icon="./pictures/DreamDropbox.png", fnc = main),
            PluginDescriptor(name = "DreamDropbox Ver. %s" % (version), description = _("Dropbox client for Enigma2"), where = PluginDescriptor.WHERE_EXTENSIONSMENU, icon="./pictures/g3icon_DreamDropbox.png", fnc=main)]
    else:
        return PluginDescriptor(name = "DreamDropbox Ver. %s" % (version), description = _("Dropbox client for Enigma2"), where = PluginDescriptor.WHERE_PLUGINMENU, icon="./pictures/DreamDropbox.png", fnc = main)

def main(session,**kwargs):
    try:
        session.open(DropBoxScreen)
    except:
        print "[DREAMDROPBOX] Pluginexecution failed"
        
class DropBoxScreen(Screen):
    raw_skin = """
        <screen position="center,{size.pos_h}" size="{size.screen}" title="{title.screen}">
            <ePixmap name="DropboxLogo" pixmap="%s/pictures/DropboxBanner_%s.png" position="{pos.dropboxlabel}" size="{size.dropboxlabel}" zPosition="4" transparent="1" alphatest="on"/>
            <eLabel text="" position="{pos.label1}" size="{size.label1}" font="Regular;14" backgroundColor="#ffffff" />
            <widget name="path" position="{pos.path}" size="{size.path}" font="Regular;%s" />
            <widget name="list" position="{pos.list}" size="{size.list}" scrollbarMode="showOnDemand" />
            <eLabel text="" position="{pos.label2}" size="{size.label2}" font="Regular;14" backgroundColor="#ffffff" />
            <widget render="Label" source= "ButtonRedText" position="{pos.but_red}" size="{size.but}" valign="center" halign="center" zPosition="5" transparent="1" foregroundColor="red" font="Regular;%s"/>
            <widget render="Label" source= "ButtonGreenText" position="{pos.but_green}" size="{size.but}" valign="center" halign="center" zPosition="5" transparent="1" foregroundColor="green" font="Regular;%s"/>
            <widget render="Label" source= "ButtonYellowText" position="{pos.but_yellow}" size="{size.but}" valign="center" halign="center" zPosition="5" transparent="1" foregroundColor="yellow" font="Regular;%s"/>
            <widget render="Label" source= "ButtonBlueText" position="{pos.but_blue}" size="{size.but}" valign="center" halign="center" zPosition="5" transparent="1" foregroundColor="blue" font="Regular;%s"/> 
        </screen>""" % (path, used_skin, int("%.0f" % (15 * scale_y)), int("%.0f" % (font_size * scale_y)), int("%.0f" % (font_size * scale_y)), int("%.0f" % (font_size * scale_y)), int("%.0f" % (font_size * scale_y)))
    
    def __init__(self, session):
        size_h_screen = y_Pos_Screen(480)
        self.dict_text = {'size.pos_h': "%.0f" % float(int(size_h_screen)), 'title.screen': "Dream Dropbox Ver. %s" % (version)}
        self.dict_var = {
            'size.screen': "500,480",
            'pos.dropboxlabel': "10,10",
            'size.dropboxlabel': "480,50",
            'pos.label1': "10,70",
            'size.label1': "480,2",
            'pos.path': "10,80",
            'size.path': "480,20",
            'pos.list': "10,100",
            'size.list': "480,320",
            'pos.label2': "10,430",
            'size.label2': "480,2",
            'size.but': "112,40",
            'pos.but_red': "10,440",
            'pos.but_green': "132,440",
            'pos.but_yellow': "254,440",
            'pos.but_blue': "376,440"
            }
        self.skin = SkinVars(DropBoxScreen.raw_skin, self.dict_text, self.dict_var)
        
        self["list"] = Menu([])
        self["path"] = Label()
        self["ButtonRedText"] = StaticText()
        self["ButtonGreenText"] = StaticText()
        self["ButtonYellowText"] = StaticText()
        self["ButtonBlueText"] = StaticText()
        self["actions"] = ActionMap(["DreamDropboxActions"], {"cancel": self.blue, "red": self.red, "green":self.green, "blue": self.blue, "yellow": self.yellow, "up": self.up, "down": self.down, "left": self.left, "right": self.right}, -1)
        
        self.session = session
        Screen.__init__(self, session)
        
        self.change = {}
        self.dir = "."
        self.dirInfo = []
        self.done = []
        self.status = "DropboxInfo"
        self.DreamPath = "/media/hdd/DropBox"
        
        if not os.path.exists(self.DreamPath):
            os.makedirs(self.DreamPath)
        
        self.onLayoutFinish.append(self.makeList)
        
    def makeList(self):
        if self.status == "DropboxInfo":
            self.dictInfo = self.DropboxInfo()
            self.setButtonText()
            self.list = []
            self.list.append(makeListDropBoxInfo(_("Name:"), self.dictInfo["Name"]))
            self.list.append(makeListDropBoxInfo(_("UID:"), self.dictInfo["UID"]))
            self.list.append(makeListDropBoxInfo(_("E-Mail:"), self.dictInfo["Email"]))
            self.list.append(makeListDropBoxInfo(_("Used space:"), self.dictInfo["Used"]))
            self.list.append(makeListDropBoxInfo(_("Total space:"), self.dictInfo["Quota"]))
            self["list"].setList(self.list)
            self["list"].selectionEnabled(0)
        elif self.status == "Drop2Dream" or self.status == "Dream2Drop":
            if self.status == "Drop2Dream" and len(self.dir.split("/")) > len(self.dirInfo):
                self.dirInfo.append(self.DropboxList())
            elif self.status == "Dream2Drop" and len(self.dir.split("/")) > len(self.dirInfo):
                self.dirInfo.append(self.osWalk())
            self.list = []
            for x in self.dirInfo[len(self.dirInfo)-1]:
                if x.startswith("[D]"):
                    tmp0 = "directory"
                    tmp1 = x.split("[D] ")[1]
                elif x.startswith("[F]"):
                    tmp1 = x.split("[F] ")[1]
                    x = "%s/%s" % (self.dir , tmp1)
                    if x not in self.change:
                        tmp0 = "file"
                    elif self.change[x]  == "1":
                        tmp0 = "file_select"
                    elif self.change[x]  == "2":
                        tmp0 = "file_delete"
                    else:
                        tmp0 = ""
                else:
                    tmp0 = ""
                self.list.append(makeListDrop2Dream(tmp0, tmp1))
            self["list"].setList(self.list)
            self["list"].selectionEnabled(1)
            self.currList = "list"
            #self["list"].moveToIndex(0)
            self.setButtonText()
        elif self.status == "DropboxUpDownload":
            self.list = []
            for key in self.change:
                if int(self.change[key]) == 1:
                    if key.startswith("./"):
                        self.list.append(makeListRunDropboxScript(_("Download:"), key, "download"))
                    elif key.startswith("/"):
                        self.list.append(makeListRunDropboxScript(_("Upload:"), key, "upload"))
                elif int(self.change[key]) == 2:
                    self.list.append(makeListRunDropboxScript(_("Delete:"), key, "delete"))
            self["list"].setList(self.list)
            if self.listenabled == 0:
                self["list"].moveToIndex(0)
                self["list"].selectionEnabled(0)
            else:
                self["list"].selectionEnabled(1)
            self.currList = "list"
            self.setButtonText()
        else:
            self.status = "DropboxInfo"
    
    def setButtonText(self):
        if self.status == "DropboxInfo":
            self["ButtonRedText"].setText(_("Drop2Dream"))
            self["ButtonGreenText"].setText(_("Dream2Drop"))
            #self["ButtonYellowText"].setText(_("Config"))
            self["ButtonYellowText"].setText(" ")
            self["ButtonBlueText"].setText(_("Exit"))
        elif self.status == "Drop2Dream" or self.status == "Dream2Drop":
            idx = self["list"].getSelectedIndex()
            self["ButtonYellowText"].setText(" ")
            if len(self.dirInfo[len(self.dirInfo)-1]) == 0:
                self["ButtonRedText"].setText(" ")
            elif self.dirInfo[len(self.dirInfo)-1][idx].startswith("[D]"):
                self["ButtonRedText"].setText(_("DirDown"))
            elif self.dirInfo[len(self.dirInfo)-1][idx].startswith("[F]"):
                tmp = "%s/%s" % (self.dir ,self.dirInfo[len(self.dirInfo)-1][idx].split("[F] ")[1])
                if tmp not in self.change:
                    self["ButtonRedText"].setText(_("Select"))
                else:
                    if self.change[tmp]  == "1":
                        self["ButtonRedText"].setText(_("Delete"))
                    else:
                        self["ButtonRedText"].setText(_("Unselect"))
            if self.dir == "." or self.dir == self.DreamPath:
                self["ButtonGreenText"].setText(" ")
            else:
                self["ButtonGreenText"].setText(_("DirUp"))
            if len(self.change) == 0:
                self["ButtonYellowText"].setText(" ")
            else:
                if self.status == "Dream2Drop":
                    self["ButtonYellowText"].setText(_("Upload Files"))
                elif self.status == "Drop2Dream":
                    self["ButtonYellowText"].setText(_("Download Files"))
                else:
                    self["ButtonYellowText"].setText(" ")
            self["ButtonBlueText"].setText(_("Back"))
            self["path"].setText(_("Path")+": %s" % self.dir)
        elif self.status == "DropboxUpDownload":
            self["ButtonRedText"].setText(_("Start"))
            if self.listenabled == 0:
                self["ButtonGreenText"].setText(" ")
            else:
                self["ButtonGreenText"].setText(_("Remove file from list"))
            self["ButtonYellowText"].setText(" ")
            self["ButtonBlueText"].setText(_("Cancel"))
            self["path"].setText(self.dir)

    def red(self):
        if self.status == "DropboxInfo":
            self.status = "Drop2Dream"
            self.makeList()
            self["list"].moveToIndex(0)
        elif self.status == "Drop2Dream" or self.status == "Dream2Drop":
            idx = self["list"].getSelectedIndex()
            if self.dirInfo[len(self.dirInfo)-1][idx].startswith("[D]"):
                self.dir = "%s/%s" % (self.dir, self.dirInfo[len(self.dirInfo)-1][idx].split("[D] ")[1])
                self["list"].moveToIndex(0)
                self.makeList()
            elif self.dirInfo[len(self.dirInfo)-1][idx].startswith("[F]"):
                tmp = "%s/%s" % (self.dir ,self.dirInfo[len(self.dirInfo)-1][idx].split("[F] ")[1])
                if tmp not in self.change:
                    self.change.update({tmp : "1"})         #1 Up/Download File
                else:
                    if self.change[tmp]  == "1":
                        self.change.update({tmp : "2"})     #2 Loesche File
                    else:
                        del self.change[tmp]                #Mache nichts mit dem File
                self.makeList()
        elif self.status == "DropboxUpDownload":
            cmd = ""
            for key in self.change:
                if int(self.change[key]) == 1:
                    if key.startswith("./"):
                        command = "%s/script/dropbox_uploader.sh download" % path
                        targetfile = "%s/%s" % (self.DreamPath, key.replace("./", ""))
                        tmp = targetfile.split("/")
                        del tmp[len(tmp)-1]
                        targetpath = ""
                        for x in tmp:
                            targetpath = "%s/%s" % (targetpath, x)
                            targetpath = targetpath.replace("//", "/")
                        if not os.path.exists(targetpath):
                            os.makedirs(targetpath)
                        if cmd == "":
                            cmd = "%s \"%s\" \"%s\"" % (command, key, targetfile)
                        else:
                            cmd = "%s && %s \"%s\" \"%s\"" % (cmd, command, key, targetfile)
                    elif key.startswith("/"):
                        commandupload = "%s/script/dropbox_uploader.sh upload" % path
                        targetfile = ".%s" % (key.replace(self.DreamPath, ""))
                        if cmd == "":
                            cmd = "%s \"%s\" \"%s\"" % (commandupload, key, targetfile)
                        else:
                            cmd = "%s && %s \"%s\" \"%s\"" % (cmd, commandupload, key, targetfile)
                elif int(self.change[key]) == 2:
                    if key.startswith("./"):
                        command = "%s/script/dropbox_uploader.sh delete" % path
                        if cmd == "":
                            cmd = "%s \"%s\"" % (command, key.replace("./", ""))
                        else:
                            cmd = "%s && %s \"%s\"" % (cmd, command, key.replace("./", ""))
                    elif key.startswith("/"):
                        if cmd == "":
                            cmd = "rm %s" % (key)
                        else:
                            cmd = "%s && rm %s" % (cmd, key)
            self.session.open(Console,_("Shell Console"), ["%s" % cmd])
            self.blue()
        else:
            pass
        
    def green(self):
        if ((self.status == "Drop2Dream" and not self.dir == ".") or (self.status == "Dream2Drop" and not self.dir == self.DreamPath)):
            del self.dirInfo[len(self.dirInfo)-1]
            tmp = self.dir.split("/")
            del tmp[len(tmp)-1]
            del tmp[0]
            self.dir = "."
            if self.status == "Dream2Drop":
                self.dir = ""
            for x in tmp:
                self.dir = "%s/%s" % (self.dir,x)
            self["list"].moveToIndex(0)
            self.makeList()
        elif self.status == "DropboxInfo":
            self.status = "Dream2Drop"
            if self.dir == ".":
                self.dir = self.DreamPath
                self["list"].moveToIndex(0)
                self.makeList()
        elif (self.status == "DropboxUpDownload" and self.listenabled == 1):
            del self.change[self.list[self["list"].getSelectedIndex()][0][1]]
            if len(self.change) == 0:
                self.blue()
            else:
                self.makeList()
                
            
            
    def yellow(self):
        if ((self.status == "Drop2Dream" or self.status == "Dream2Drop") and len(self.change) > 0):
            if self.status == "Drop2Dream":
                self.dir = _("Download files to the Dreambox or delete files in the Dropbox account")
            elif self.status == "Dream2Drop":
                self.dir = _("Upload files to the Dropbox account or delete files on the Dreambox ")
            self.status = "DropboxUpDownload"
            self.listenabled = 0
            self.makeList()
        
    def blue(self):
        if self.status == "DropboxInfo":
            self.close()
        else:
            self.status = "DropboxInfo"
            self.dir = "."
            self.dirInfo = []
            self.done = []
            self.change = {}
            self["path"].setText("")
            self.makeList()
        
    def up(self):
        if self.status == "Drop2Dream" or self.status == "Dream2Drop" or (self.status == "DropboxUpDownload" and self.listenabled == 1):
            self[self.currList].up()
            self.setButtonText()
        elif self.status == "DropboxUpDownload":
            if self.listenabled == 0:
                self.listenabled = 1
                self.makeList()
                
            
        
    def down(self):
        if self.status == "Drop2Dream" or self.status == "Dream2Drop" or (self.status == "DropboxUpDownload" and self.listenabled == 1):
            self[self.currList].down()
            self.setButtonText()
        elif self.status == "DropboxUpDownload":
            if self.listenabled == 0:
                self.listenabled = 1
                self.makeList()
        
    def left(self):
        if self.status == "Drop2Dream" or self.status == "Dream2Drop" or (self.status == "DropboxUpDownload" and self.listenabled == 1):
            self[self.currList].pageUp()
            self.setButtonText()
        
    def right(self):
        if self.status == "Drop2Dream" or self.status == "Dream2Drop" or (self.status == "DropboxUpDownload" and self.listenabled == 1):
            self[self.currList].pageDown()
            self.setButtonText()
        
    def osWalk(self):
        res = []
        for t in os.walk(self.dir):
            if len(t[1]) == 0 and len(t[2]) == 0:
                pass
            else:
                try:
                    if len(t[1]) >= 1:
                        for x in t[1]:
                            res.append("[D] %s" % x)
                except:
                    pass
                try:
                    if len(t[2]) >= 1:
                        for x in t[2]:
                            res.append("[F] %s" % x)
                except:
                    pass
                res.sort()
                return res
                break
        return res
        
    def DropboxInfo(self):
        res = {"Name":"", "UID":"", "Email":"", "Used":"", "Quota":""}
        process = subprocess.Popen(["%s/script/dropbox_uploader.sh" % path, "info"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while True:
            out = process.stdout.read()
            if out == '' and process.poll() != None:
                break
            if out != '':
                out = out.split("\n")
                for x in out:
                    x = x.strip().replace("\t","").split(":")
                    if len(x) == 1:
                        pass
                    else:
                        res.update({x[0] : x[1]})
                if "Quota" in res:
                    x = int(res["Quota"])/1048576
                    res.update({"Quota" :"%sMB" % x})
                if "Used" in res:
                    x = int(res["Used"])/1048576
                    res.update({"Used" :"%sMB" % x})
        return res
    
    def DropboxList(self):
        res = []
        out = []
        process = subprocess.Popen(["%s/script/dropbox_uploader.sh" % path, "list", "%s"  % self.dir], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out.append(process.stdout.read().split("\n"))
        if out != '':
            for x in out[0]:
                x = x.strip()
                if x.startswith(">") or x == (""):
                    pass
                else:
                    x = x.replace("\n","")
                    res.append(x)
        res.sort()
        return res

#Formatierung
class Menu(MenuList):
    def __init__(self, items, enableWrapAround = False):
        MenuList.__init__(self, items, enableWrapAround, eListboxPythonMultiContent)
        self.l.setFont(0, gFont("Regular", int("%.0f" % (font_size * scale_y))))
        self.l.setFont(1, gFont("Regular", int("%.0f" % ((font_size -2)  * scale_y))))
        self.l.setFont(2, gFont("Regular", int("%.0f" % ((font_size -4)  * scale_y))))
        self.l.setItemHeight(int("%.0f" % (font_size * scale_y)))
        
def makeListDropBoxInfo(tmp0, tmp1):
    res = [(tmp0, tmp1)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(220 * scale_x, int("%.0f" % (font_size * scale_y))), font=0, flags = RT_HALIGN_LEFT, text=tmp0))
    res.append(MultiContentEntryText(pos=(230, 0), size=(270 * scale_x, int("%.0f" % (font_size * scale_y))), font=0, flags = RT_HALIGN_LEFT, text=tmp1))
    return res

def makeListDrop2Dream(tmp0, tmp1):
    res = [(tmp1)]
    png1 = "%s/pictures/%s_%s.png" % (path, tmp0, used_skin)
    if fileExists(png1):
        res.append(MultiContentEntryPixmapAlphaTest(pos = (0, 2), size = (16* scale_x, 16* scale_y), png = loadPNG(png1)))
    tmp0 = splitString(tmp0)
    res.append(MultiContentEntryText(pos=(20 * scale_x, 0), size=(460 * scale_x, int("%.0f" % (font_size * scale_y))), font=0, flags = RT_HALIGN_LEFT, text=tmp1))
    return res

def makeListRunDropboxScript(tmp0, tmp1, tmp2):
    res = [(tmp0, tmp1)]
    try:
        if tmp2 == "delete":
            color = 0xcd0000  #red3
        elif tmp2 == "download":
            color = 0x00cd00  #green3
        elif tmp2 == "upload":
            color = 0x1874CD  #DodgerBlue3
        else:
            color = 0xffffff  #gray100
    except:
        color = 0xffffff  #gray100
    res.append(MultiContentEntryText(pos=(0, 0), size=(140 * scale_x, int("%.0f" % (font_size * scale_y))), font=2, flags = RT_HALIGN_LEFT, text=tmp0, color=color))
    res.append(MultiContentEntryText(pos=(150, 0), size=(330 * scale_x, int("%.0f" % (font_size * scale_y))), font=2, flags = RT_HALIGN_LEFT, text=tmp1, color=color))
    return res

def makeListDone(tmp0, tmp1):
    res = [(tmp0, tmp1)]
    res.append(MultiContentEntryText(pos=(0, 0), size=(180 * scale_x, int("%.0f" % (font_size * scale_y))), font=2, flags = RT_HALIGN_LEFT, text=tmp0))
    res.append(MultiContentEntryText(pos=(190, 0), size=(290 * scale_x, int("%.0f" % (font_size * scale_y))), font=2, flags = RT_HALIGN_LEFT, text=tmp1))
    return res

def splitString(x):
    if x.startswith("[D]"):
        x = x.split("[D] ")[1]
    elif x.startswith("[F]"):
        x = x.split("[F] ")[1]
    return x

def SkinVars(skin, dict_text, dict_var):
    for key in dict_text.keys():
        skin = skin.replace('{'+key+'}',dict_text[key])
    for key in dict_var.keys():
        if used_skin == "hd":
            skin = skin.replace('{'+key+'}',"%.0f,%.0f" % ((float(dict_var[key].split(',')[0]) * scale_x), (float(dict_var[key].split(',')[1]) * scale_y)))
        else:
            skin = skin.replace('{'+key+'}',dict_var[key])
    return skin

def y_Pos_Screen(y_size_screen):
    size_h = int(getDesktop(0).size().height())
    size_h_screen = (size_h - scale_y * int(y_size_screen)) / 2 + int(offset)
    return size_h_screen

def debug(debug):
    f = open("/hdd/debug.txt" , "a")
    f.write("%s\n" % debug)
    f.close()
